import os
# -*- coding: utf-8 -*-
# flake8: noqa
from qiniu import Auth, urlsafe_base64_encode, put_file
from elasticsearch import Elasticsearch

import pymysql

# 连接数据库
db = pymysql.connect(
    host="127.0.0.1",
    port=3306,
    user="root",
    password="010401",
    database="qiniu",
    charset="utf8mb4"
)

cursor = db.cursor(cursor=pymysql.cursors.DictCursor)

q = Auth('wkJupck8Ylduede0ny9KSsIG4vqwDkelgBfejKSv', 'i4UrEdihv93LUun8MMG_OCAcGQHwPU6ZiHq5ijMg')
bucket = 'wxapptest'
prefix_key = 'qiniu/'
prefix_cover = 'qiniu/vframe/'
pfop_mp4 = 'avthumb/mp4/s/640x360/vb/1.25m|saveas/'
pfop_jpg = 'vframe/jpg/offset/1/w/480/h/360|saveas/'

l = []

es = Elasticsearch(["http://localhost:9200"])  # 替换成你的 Elasticsearch 地址


def remove_file_extension(filename):
    base_name, extension = os.path.splitext(filename)
    return base_name


for i in range(1, 13, 1):
    for root, dirs, files in os.walk(f'./视频/{i}'):
        for file in files:
            file_path = os.path.join(root, file)
            ofile = remove_file_extension(file)
            key = prefix_key + file
            cover = prefix_cover + ofile + ".jpg"
            fops = pfop_mp4 + urlsafe_base64_encode(bucket + ':' + key) + ';' + urlsafe_base64_encode(
                bucket + ":" + cover)
            policy = {
                'persistentOps': fops,
                'persistentPipeline': 'ts-admin-pipleline'
            }
            ret, info = put_file(q.upload_token(bucket, key, 3600, policy), key, file_path, version='v2')
            l.append({'key': key, 'hash': ret['hash'], 'type': i, 'title': ofile, 'uid': 1, 'cover': cover})
            # 插入数据库
            for obj in l:
                try:
                    # 新增一条记录
                    sql = f"insert into video(`key`,`hash`,`type`,`title`,`uid`,`cover`) values('{obj['key']}', '{obj['hash']}',{obj['type']},'{obj['title']}', {obj['uid']}, '{obj['cover']}')"
                    cursor.execute(sql)
                    db.commit()
                except Exception as e:
                    db.rollback()
            # 插入es
            es.create(index="es_qiniu", id=f'{i}', body={"title": ofile, "id": i})

# 关闭光标对象
cursor.close()

# 关闭数据库连接
db.close()
